import axios from "axios";
import Loading from "@/utils/Loading.jsx";

let store;
const initStore = async () => {
  if (!store) {
    const module = await import("@/store");
    store = module.store;
  }
  return store;
};
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: import.meta.env.VITE_APP_TIMEOUT,
  headers: {
    "Content-Type": "application/json;charset=utf-8",
  },
});
service.interceptors.request.use(
  async (config) => {
    await initStore();
    const token = store.getState().userStore.token;
    if (config.Loading) {
      console.log(Loading());
      Loading().showLoading("数据加载中");
    }
    if (token) {
      config.headers["Authorization"] = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);
service.interceptors.response.use(
  (response) => {
    const { code } = response.data;
    if (code === 200) {
      Loading().hideLoading();
      return response.data;
    }
  },
  (error) => {
    return Promise.reject(error);
  },
);
export default service;
